package org.chen.wordwave.fragment;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.hjq.toast.Toaster;
import com.yalantis.ucrop.UCrop;

import org.chen.wordwave.R;
import org.chen.wordwave.act.AboutMe;
import org.chen.wordwave.act.FavoriteWordsAct;
import org.chen.wordwave.act.Favorites;
import org.chen.wordwave.act.FeedbackAct;
import org.chen.wordwave.act.FrequentlyAskedQuestions;
import org.chen.wordwave.act.Login;
import org.chen.wordwave.act.MemberCenter;
import org.chen.wordwave.act.Privacy;
import org.chen.wordwave.act.ReservationList;
import org.chen.wordwave.act.Setting;
import org.chen.wordwave.act.User;
import org.chen.wordwave.act.VersionUpgrade;
import org.chen.wordwave.bean.FavoriteWords;
import org.chen.wordwave.bean.Reservation;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.bean.Words;
import org.chen.wordwave.init.WordInit;
import org.litepal.LitePal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class AboutMeFragment extends Fragment {
    private static final String PREFS_NAME = "UserPrefs";
    private static final String KEY_AVATAR_PATH = "avatarPath";
    private TextView tv_userPhone, tv_registeTime, user, privacy, tv_userName,vip;
    private LinearLayout ll_my_favorite_words, myf, Appointment,my_vip;
    private Context context;
    private ImageView iv_mysetting;
    private ImageView ivAvatar;
    private RelativeLayout rl_logout, rl_about_us, rl_problem, rl_suggest, rl_version, rl_share;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    // 添加 Google 客户端
    private GoogleSignInClient mGoogleSignInClient;

    @SuppressLint("SetTextI18n")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_aboutme, container, false);
        context = getActivity();

        // 初始化 Google Sign In Client
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(requireActivity(), gso);

        initView(view);

        tv_userName.setText(getString(R.string.userName) + WordInit.userInfo.getAccount());
        tv_userPhone.setText(getString(R.string.user) + WordInit.userInfo.getEmail());
        tv_registeTime.setText(getString(R.string.register_time) + WordInit.userInfo.getRegisterTime());

        ll_my_favorite_words.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<FavoriteWords> favoriteWords = LitePal.where("email = ?", WordInit.userInfo.getEmail()).find(FavoriteWords.class);
                List<Words> wordsList = new ArrayList<>();
                for (FavoriteWords favoriteWords1 : favoriteWords) {
                    wordsList.add(LitePal.where("id = ?", String.valueOf(favoriteWords1.getWordsId())).findFirst(Words.class));
                }
                Intent intent = new Intent(context, FavoriteWordsAct.class);
                intent.putExtra("favWords", (Serializable) wordsList);
                startActivity(intent);
            }
        });
        rl_about_us.setOnClickListener((e) -> {
            Intent intent = new Intent(getContext(), AboutMe.class);
            startActivity(intent);

        });
        rl_problem.setOnClickListener((e) -> {
            Intent intent = new Intent(getContext(), FrequentlyAskedQuestions.class);
            startActivity(intent);

        });
        rl_suggest.setOnClickListener((e) -> {
            Intent intent = new Intent(getContext(), FeedbackAct.class);
            startActivity(intent);

        });
        rl_version.setOnClickListener((e) -> {
            Intent intent = new Intent(getContext(), VersionUpgrade.class);
            startActivity(intent);

        });
        myf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, Favorites.class));
            }
        });

        rl_logout.setOnClickListener(v -> showLogoutDialog());

        iv_mysetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, Setting.class));
            }
        });

        user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, User.class));
            }
        });

        privacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, Privacy.class));
            }
        });

        Appointment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Reservation> reservations = LitePal.where("userEmail = ?", WordInit.userInfo.getEmail()).find(Reservation.class);
                Intent intent = new Intent(context, ReservationList.class);
                intent.putExtra("reservations", (Serializable) reservations);
                startActivity(intent);
            }
        });
        my_vip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MemberCenter.class);
                startActivity(intent);
            }
        });
        UserInfo currentUser = getCurrentUser();
        if (currentUser.isMember() && currentUser.getMembershipExpiryDate() != null){
            vip.setText(getString(R.string.mine_vip) + dateFormat.format(currentUser.getMembershipExpiryDate()));
        }

        loadUserInfoAndUpdateUI();
        return view;
    }

    private void showLogoutDialog() {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(context);
        normalDialog.setIcon(R.mipmap.wring);
        normalDialog.setTitle(R.string.exit);
        normalDialog.setMessage(R.string.are_you_exit);
        normalDialog.setPositiveButton(R.string.yes, (dialog, which) -> performLogout());
        normalDialog.setNegativeButton(R.string.close, null);
        normalDialog.show();
    }

    private void initView(View view) {
        tv_userPhone = view.findViewById(R.id.tv_userEmail);
        tv_registeTime = view.findViewById(R.id.tv_registeTime);
        ll_my_favorite_words = view.findViewById(R.id.ll_my_favorite_words);
        rl_logout = view.findViewById(R.id.rl_logout);
        rl_about_us = view.findViewById(R.id.rl_about_us);
        rl_problem = view.findViewById(R.id.rl_problem);
        rl_suggest = view.findViewById(R.id.rl_suggest);
        rl_version = view.findViewById(R.id.rl_version);
        iv_mysetting = view.findViewById(R.id.iv_mysetting);
        myf = view.findViewById(R.id.myf);
        user = view.findViewById(R.id.user);
        privacy = view.findViewById(R.id.privacy);
        tv_userName = view.findViewById(R.id.tv_userName);
        Appointment = view.findViewById(R.id.Appointment);
        my_vip = view.findViewById(R.id.my_vip);
        vip = view.findViewById(R.id.vip);
        ivAvatar = view.findViewById(R.id.iv_avatar);
    }

    private UserInfo getCurrentUser() {
        // 获取当前用户，例如通过SharedPreferences存储的email等信息
        String email = WordInit.userInfo.getEmail();
        return LitePal.where("email = ?", email).findFirst(UserInfo.class);
    }

    @Override
    public void onResume() {
        super.onResume();
        checkMembershipStatus();
        loadUserInfoAndUpdateUI();
    }

    private void checkMembershipStatus() {
        UserInfo currentUser = getCurrentUser();
        if (currentUser.isMember() && currentUser.getMembershipExpiryDate() != null) {
            // 检查会员是否过期
            Date currentDate = new Date();
            if (currentDate.after(currentUser.getMembershipExpiryDate())) {
                currentUser.setMember(false);
                currentUser.setMembershipExpiryDate(null);
                currentUser.save();
                updateMembershipStatus(getString(R.string.my_member_you_are_currently_not_a_member));
            } else {
                String formattedDate = dateFormat.format(currentUser.getMembershipExpiryDate());
                updateMembershipStatus(getString(R.string.my_vip_about) + formattedDate);
            }
        } else {
            updateMembershipStatus(getString(R.string.my_member_you_are_currently_not_a_member));
        }
    }

    private void updateMembershipStatus(String status) {
        vip.setText(status);
    }

    private void loadAvatar() {
        SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String avatarPath = prefs.getString(KEY_AVATAR_PATH, null);
        if (avatarPath != null) {
            Uri uri = Uri.parse(avatarPath);
            ivAvatar.setImageURI(uri);
        }
    }

    @SuppressLint("SetTextI18n")
    private void loadUserInfoAndUpdateUI() {
        UserInfo currentUser = getCurrentUser();
        if (currentUser != null) {
            tv_userName.setText(getString(R.string.userName) + currentUser.getAccount());
            tv_userPhone.setText(getString(R.string.user) + currentUser.getEmail());
            tv_registeTime.setText(getString(R.string.register_time) + currentUser.getRegisterTime());

            if (currentUser.isMember() && currentUser.getMembershipExpiryDate() != null) {
                String formattedDate = dateFormat.format(currentUser.getMembershipExpiryDate());
                updateMembershipStatus(getString(R.string.my_vip_about) + formattedDate);
            } else {
                updateMembershipStatus(getString(R.string.my_member_you_are_currently_not_a_member));
            }

            // 加载存储的头像路径
            loadAvatar();
        }
    }

    private void performLogout() {
        // 显示加载对话框
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage(getString(R.string.logging_out));
        progressDialog.setCancelable(false);
        progressDialog.show();

        // 检查是否是Google登录用户
        UserInfo currentUser = getCurrentUser();
        if (currentUser != null && currentUser.getGoogleId() != null) {
            // Google登录用户，需要同时注销Google账号
            mGoogleSignInClient.signOut()
                    .addOnCompleteListener(requireActivity(), task -> {
                        clearUserDataAndRedirect();
                        progressDialog.dismiss();
                    })
                    .addOnFailureListener(e -> {
                        // 即使Google注销失败，仍然清除本地数据
                        clearUserDataAndRedirect();
                        progressDialog.dismiss();

                        // 显示错误提示
                        Toast.makeText(context,
                                getString(R.string.google_logout_failed),
                                Toast.LENGTH_SHORT).show();
                    });
        } else {
            // 普通登录用户，直接清除数据
            clearUserDataAndRedirect();
            progressDialog.dismiss();
        }
    }

    private void clearUserDataAndRedirect() {
        // 清除SharedPreferences中的数据
        WordInit.flyerEditor.clear();
        WordInit.flyerEditor.commit();

        // 清除用户信息
        WordInit.userInfo.setEmail(null);
        WordInit.userInfo.setGoogleId(null);

        // 清除数据库中的用户数据
        LitePal.deleteAll(UserInfo.class);

        // 清除头像缓存
        SharedPreferences prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().remove(KEY_AVATAR_PATH).apply();

        // 跳转到登录界面
        Intent intent = new Intent(context, Login.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);

        // 结束当前Activity
        if (getActivity() != null) {
            getActivity().finish();
        }
    }
}
